196B - Infinite Maze - CodeForces Solution


dfs and similar graphs *2000

Please click on ads to support us..

C++ Code:

#include <iostream>

using namespace std;

const int N = 5000;
int a, b, n, m;
int dx[4] = {0, 1, -1, 0};
int dy[4] = {1, 0, 0, -1};
char s[N][N];
bool mark[N][N];

void dfs(int x, int y) {
    mark[x][y] = true;
    for (int i = 0; i < 4; i++) {
        int X = x + dx[i], Y = y + dy[i];
        X = (X + 3 * n) % (3 * n);
        Y = (Y + 3 * m) % (3 * m);
        if (s[X][Y] != '#' && !mark[X][Y]) {
            if (s[X][Y] == 'S') {
                cout << "Yes\n";
                exit(0);
            }
            dfs(X, Y);
        }
    }
}

int main() {
    cin >> n >> m;
    for (int i = n; i < 2 * n; i++) {
        for (int j = m; j < 2 * m; j++) {
            cin >> s[i][j];
            if (s[i][j] == 'S') {
                a = i, b = j;
            }
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            s[i][j] = s[i + n][j + m];
        }
    }

    for (int i = n; i < 2 * n; i++) {
        for (int j = 0; j < m; j++) {
            s[i][j] = s[i][j + m];
        }
    }

    for (int i = 2 * n; i < 3 * n; i++) {
        for (int j = 0; j < m; j++) {
            s[i][j] = s[i - n][j + m];
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 2 * m; j < 3 * m; j++) {
            s[i][j] = s[i + n][j - m];
        }
    }

    for (int i = n; i < 2 * n; i++) {
        for (int j = 2 * m; j < 3 * m; j++) {
            s[i][j] = s[i][j - m];
        }
    }

    for (int i = 2 * n; i < 3 * n; i++) {
        for (int j = 2 * m; j < 3 * m; j++) {
            s[i][j] = s[i - n][j - m];
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = m; j < 2 * m; j++) {
            s[i][j] = s[i + n][j];
        }
    }

    for (int i = 2 * n; i < 3 * n; i++) {
        for (int j = m; j < 2 * m; j++) {
            s[i][j] = s[i - n][j];
        }
    }
    dfs(a, b);
    cout << "No\n";
    return 0;
}


Comments

Submit
0 Comments
More Questions

112. Path Sum
1556A - A Variety of Operations
136. Single Number
169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings
1002. Find Common Characters
1602A - Two Subsequences
1555A - PizzaForces
1607B - Odd Grasshopper
1084A - The Fair Nut and Elevator
1440B - Sum of Medians
1032A - Kitchen Utensils
1501B - Napoleon Cake
1584B - Coloring Rectangles
1562B - Scenes From a Memory
1521A - Nastia and Nearly Good Numbers
208. Implement Trie